/*
 * Copyright (C) 2012 The Android Open Source Project
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *      http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */
package com.example.android.news;

import java.net.MalformedURLException;
import java.net.URL;

import java.util.LinkedList;
import java.util.List;
import com.example.android.news.RssParser.Item;
import com.example.android.news.RssParser.RssFeed;

import android.content.res.Resources;
import android.os.Bundle;
import android.view.View;

import android.widget.ArrayAdapter;
import android.widget.ListView;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentManager;
import android.support.v4.app.FragmentManager.BackStackEntry;
import android.support.v4.app.FragmentTransaction;
import android.support.v4.app.ListFragment;
import android.util.Log;

public class CategoryFragment extends ListFragment {
    private static final String TAG = "CategoryFragment";

    int mCategory = 0;
    int mCurPosition = 0;
    int mCategoryEntry;
    private MainActivity mActivity;
    private Resources mResources;
    private List<String>  mPositionVsUrl;
    List<DirectoryEntry> mCategoryEntryObj;
    
    private String mSrcOneA;
    private String mSrcOneB;
    private String mSrcOneC;
    private String mSrcTwoA;
    private String mSrcTwoB;
    private String mSrcTwoC;
    private String mSrcThreeA;
    private String mSrcThreeB;
    private String mSrcThreeC;
    private String mSrcFourA;
    private String mSrcFourB;
    private String mSrcFourC;
    private String[] mSrcOne = new String[3];
    private String[] mSrcTwo = new String[3];
    private String[] mSrcThree = new String[3];
    private String[] mSrcFour = new String[4];
    
    public CategoryFragment() {
        mPositionVsUrl = new LinkedList<String>();
        mCategoryEntryObj = new LinkedList<DirectoryEntry>();
    }
    @Override
    public void onActivityCreated(Bundle savedInstanceState) {
        super.onActivityCreated(savedInstanceState);
        init();
        populateTitles();
        ListView lv = getListView();
        lv.setChoiceMode(ListView.CHOICE_MODE_SINGLE);
        lv.setSelected(true);
        Bundle bundle = ((MainActivity)getActivity()).savedInstanceState;
        if(bundle != null) {
            String detailsfragment = bundle.getString("DetailsFragment");
            String url = bundle.getString("url");
            if(detailsfragment != null) {
                if(detailsfragment.endsWith("DetailsFragment")) {
                    Fragment fragment = getActivity().getSupportFragmentManager().findFragmentById(
                            R.id.details_fragment);
                    FragmentManager manager = getActivity().getSupportFragmentManager();
                    int count  = manager.getBackStackEntryCount();
                    for(int i = 0 ; i < count ; i++) {
                        BackStackEntry entry = manager.getBackStackEntryAt(0);
                        Log.d(TAG, "Backstack entry:" +  entry.getBreadCrumbTitleRes());
                    }
                }else {
                    ((MainActivity)getActivity()).loadWebViewFragment(url);
                }
            }
        }else {
            if(!mActivity.mSinglePane) {
                updateDetailView(0);
            }
        }
    }

    public void selectPosition(int position) {
        ListView lv = getListView();
        lv.setItemChecked(position, true);

        updateDetailView(position);
    }
    
    public void populateTitles() {
        int catCount = Directory.getCategoryCount();
        List<String> items = new LinkedList<String>();
        for(int i = 0; i < catCount; i++) {
            DirectoryCategory cat = Directory.getCategory(i);
            mCategory = i;
            for (int j = 0; j < cat.getEntryCount(); j++) {
                String item = cat.getName() + " : " + cat.getEntry(j).getName();
                items.add(item);
                mPositionVsUrl.add(cat.getEntry(j).getUrl());
                mCategoryEntryObj.add(cat.getEntry(j));
                mCategoryEntry = j;
            }   
        }
        String[] itemsArray = new String[items.size()];
        items.toArray(itemsArray);
        setListAdapter(new ArrayAdapter<String>(getActivity(),
                R.layout.left_list_item, itemsArray));
    }

    private void updateContent(String urlStr){
        try {	
            URL url = new URL(urlStr);
            new DownloadFilesTask((MainActivity)getActivity()).execute(url);
        } catch (MalformedURLException e) {
            Log.e(TAG,"Exception", e);
        } catch(Exception e) {
            Log.e(TAG,e.toString(), e);
        }
    }
    @Override
    public void onListItemClick(ListView l, View v, int position, long id) {
        Log.e(TAG,"inside ListItemClicked");
        updateDetailView(position);
    }
    private void updateDetailView(int position) {
        Log.d(TAG,"inside updateWebView" );
        Long currentTime = new Long(System.currentTimeMillis());
        DirectoryCategory category = Directory.getCategory(mCategory);
        String url = null;
        if(mActivity!=null) {

        url = mPositionVsUrl.get(position);
        long lastUpdatedTime = mCategoryEntryObj.get(position).getLastUpdatedTime();
        try {
            Log.d(TAG, "inside updateWebView:else");
            long timeDiff = currentTime - lastUpdatedTime;
            if(lastUpdatedTime == 0){
                updateContent(url);
            }else {
                if(timeDiff > 2*60*1000) {
                    updateContent(url);
                }else {
                    List<Item> newsItems = mCategoryEntryObj.get(position).getNewsItems();

                    FragmentManager fragmentManager = getFragmentManager();

                    DetailsFragment detailsFragment = new DetailsFragment();
                    FragmentTransaction fragmentTransaction = fragmentManager.beginTransaction();
                    
                    fragmentTransaction.replace(R.id.details_fragment, detailsFragment);
                    
                    fragmentTransaction.addToBackStack(null);
                    fragmentTransaction.commit();
                    detailsFragment.setDataList(newsItems);
                }
            }
        } catch (Exception e) {
            Log.e(TAG, "Exception in updateWebView", e);
        }
        mCurPosition = position;	
        }
    }

    private void init() {
        mActivity = (MainActivity) getActivity();
        mResources = mActivity.getResources();
        mSrcOneA = mResources.getString(R.string.src_one_a_url);
        mSrcOneB = mResources.getString(R.string.src_one_b_url);
        mSrcOneC = mResources.getString(R.string.src_one_c_url);

        mSrcOne[0] = mSrcOneA;
        mSrcOne[1] = mSrcOneB;
        mSrcOne[2] = mSrcOneC;
    }
}

class Downloader {
    static String TAG = "Downloader";

    protected static List downloadFile(URL url) {
        Log.d(TAG, "download begining");
        Log.d(TAG, "download url:" + url);
        String urlStr = url.toString();
        return parseAndUpdate2(urlStr);
    }

    private static List parseAndUpdate2(String url) {
        RssParser rp = new RssParser(url);
        rp.parse();
        RssFeed feed = rp.getFeed();
        return feed.items;
    }
}


